<template>
	<view class="content">
		<view class="vip-option-list">
			<view class="vip-option" v-for="(item, index) in vip" :key="index">
				<view class="info-wrap">
					<text class="title">{{item.day}}天尊贵身份</text>
					<view class="price">￥{{item.money}}</view>
				</view>
				<button class="pay-btn" type="primary" size="mini" @click="requestOrder(item)">{{getPrice(item)}}元/天</button>
			</view>
		</view>
		<view class="vip-intro">
			<view class="intro-title">会员特权</view>
			<view class="intro-list">
				<view class="intro-item" v-for="(item, index) in intro" :key="index">
					<image class="intro-icon" :src="qiniu.domain+item.image" mode=""></image>
					<view class="intro-info">
						<view class="title">特权{{index+1}}</view>
						<view class="desc">{{item.content}}</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { JSEncrypt } from 'jsencrypt/bin/jsencrypt';
	export default {
		data() {
			return {
				myInfo: {},
				platform: '',
				vip: [],
				
				intro:[],
				
				viparr:[],
				// 七牛云相关配置
				qiniu:{
					token: '',
					domain: '',
					expires: ''
				},
				
				iapChannel: null,
				product_list: '',
			}
		},
		onLoad(options) {
			try {
				const myInfo = uni.getStorageSync('myInfo');
				if (myInfo) {
					this.myInfo = myInfo
				}
			} catch (e) {
				console.log(e)
			}
			try {
				const systemInfo = uni.getSystemInfoSync();
				if (systemInfo) {
					this.platform = systemInfo.platform
				}
			} catch (e) {
				console.log(e)
			}
			this.getIPA();  //获取支付渠道
		},
		onReady() {
			this.getVip();
			this.getViparr();
			this.updateQiniuToken()
		},
		methods: {
			// 获取七牛云域名
			updateQiniuToken: function () {
				let timestamp = (new Date()).getTime();
				let _this = this;
				this.$api.api.ajaxData({
					method: 'V1.QiniuToken',
					uid: this.myInfo.id,
					token: this.myInfo.token,
				}, res => {
					if (res.status) {
						let expires = timestamp + res.data.expires*1000;
						this.qiniu = {
							token: res.data.token,
							domain: res.data.domain,
							expires: expires
						}
					} else {
						_this.prompt(res.msg);
					}
				})
			},
			getVip: function () {
				uni.showLoading({
					title: ''
				});
				this.$api.api.ajaxData({
					method: 'V1.Vip',
					uid: this.myInfo.id,
					token: this.myInfo.token,
					page: 1
				}, res => {
					uni.hideLoading();
					if (res.status) {
						this.vip = res.data.list;
						console.log('返回的vip数组',res.data.list)
					}
				}, err => {
					uni.hideLoading();
					uni.showToast({
						title: '网络错误，请稍后再试',
						position: 'bottom',
						icon: 'none'
					});
				})
			},
			
			getPrice(item) {
				let money = parseFloat(item.money);
				let day = parseInt(item.day);
				return (money/day).toFixed(2);
			},
			
			// 获取特权数组
			getViparr: function () {
				uni.showLoading({
					title: ''
				});
				var that=this;
				that.$api.api.ajaxData({
					method: 'V1.VipPrivilege',
					
				}, res => {
					// console.log('特权数组返回',res)
					uni.hideLoading();
					if (res.status) {
						that.intro=res.data;
					}
				}, err => {
					uni.hideLoading();
					uni.showToast({
						title: '网络错误，请稍后再试',
						position: 'bottom',
						icon: 'none'
					});
				})
			},
			
			getIPA: function () {
			    plus.payment.getChannels(channels => {
			        // 获取苹果内购渠道
			        for (let i = 0; i < channels.length; i++) {
						if (channels[i].id == 'appleiap') {
						    this.iapChannel = channels[i];
							this.restoreComplateRequest();
							
						}  
			        }
			    }, e => {  
			        console.log("获取支付通道失败：", e);  
			    });
			},
			
			// 创建内购项目订单
			requestOrder:function(item) {
			    var _this=this;
				if(item.apple_id=="" ){
					uni.showToast({
						title: '后台未配置苹果支付id，暂不能支付',
						position: 'bottom',
						icon: 'none'
					});
					return
				}
				uni.showLoading({
					title: '正在创建订单请稍后....'
				});
			    _this.iapChannel.requestOrder(
			        [item.apple_id],
			        res => {
						uni.hideLoading()
						_this.product_list = res;
					    _this.payFun(res);
						
			        },
			        function(errormsg) {
			            plus.nativeUI.alert("获取应用内购项目失败，请稍后重试。", function() {}, "提示");
			        }
			    )
			},
			
			// 调起支付
			payFun: function(i) {
				uni.showLoading({
					title: '拉起支付'
				});
				setTimeout(function(){
					uni.hideLoading()
				},2000)
				
			    let _this=this;
			    plus.payment.request(_this.iapChannel, {
					 productid: i[0].productid,
					 optimize: true ,      // 支付时设置 optimize: true  
					}, 
					function(result){
						
						uni.showToast({
							title: '支付成功',
							position: 'bottom',
							icon: 'none'
						});
						
						var cc=_this.enphone(JSON.stringify(result));
						uni.request({
							url: 'http://atm.sanfuhai.cn/api/ios',
							method: 'POST',
							header: {'content-type': 'application/x-www-form-urlencoded'},
							data: {form:cc,type:'vip',uid: _this.myInfo.id,},
							success: res => {
								uni.hideLoading();
								if (res.statusCode == 200) {
									if(res.data=='success'){
										//更新米币数量
										uni.$emit('my-page', {
											type: 'update',
										})
									}
								}
							},
							fail: err => {
								console.log('失败返回信息',err)
							}
						})		
						
					}, function(e){
						// 用户取消支付或者调起支付失败回调
						_this.restoreComplateRequest()
			        });	
			},
			
			// 获取已购的非消耗性商品和订阅商品
			restoreComplateRequest: function() {
				this.iapChannel.restoreComplateRequest({}, results => {
					// results 格式为数组存放恢复的IAP商品交易信息对象 IAPTransaction，通用需将返回的支付凭证传给后端进行二次认证  
					uni.showToast({
						title: '11111支付成功回调'+JSON.stringify(results),
						position: 'bottom',
						icon: 'none'
					});
					
				}, e => {
					uni.showToast({
						title: '失败回调'+JSON.stringify(e),
						position: 'bottom',
						icon: 'none'
					});
					
				});
			},   
			// 加密
			enphone(msg){
				let pubkey = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDAbfx4VggVVpcfCjzQ+nEiJ2DLnRg3e2QdDf/m/qMvtqXi4xhwvbpHfaX46CzQznU8l9NJtF28pTSZSKnE/791MJfVnucVcJcxRAEcpPprb8X3hfdxKEEYjOPAuVseewmO5cM+x7zi9FWbZ89uOp5sxjMnlVjDaIczKTRx+7vn2wIDAQAB-----END PUBLIC KEY-----'; // 公钥
				var encrypt = new JSEncrypt();
				encrypt.setPublicKey(pubkey);
				return encrypt.encrypt(msg);
			},
			
		}
	}
</script>

<style lang="scss">
	@import '../../common/common.scss';
	.vip-option-list {
		margin: 20rpx;
		background-color: #fff;
		border-radius: 20rpx;
		.vip-option {
			display: flex;
			justify-content: flex-start;
			align-items: center;
			padding: 20rpx;
			& + .vip-option {
				border-top: 1rpx solid $border-light-color;
			}
			.info-wrap {
				display: flex;
				flex-direction: column;
				justify-content: flex-start;
				align-items: flex-start;
				flex: 1;
				.title {
					font-size: 36rpx;
					color: $title-color;
				}
				.price {
					font-size: 28rpx;
					color: $title-color;
				}
			}
			.pay-btn {
				border-radius: 100rpx;
			}
		}
	}
	
	.vip-intro {
		.intro-title {
			font-size: 36rpx;
			color: $title-color;
			margin: 20rpx 30rpx;
		}
		.intro-list {
			margin: 0 20rpx;
			background: #fff;
			border-radius: 20rpx;
			.intro-item {
				display: flex;
				justify-content: flex-start;
				align-items: center;
				padding: 20rpx;
				& + .intro-item {
					border-top: 1rpx solid $border-light-color;
				}
				.intro-icon {
					width: 80rpx;
					height: 80rpx;
					margin-right: 20rpx;
				}
				.intro-info {
					.title {
						font-size: 32rpx;
						color: $title-color;
					}
					.desc {
						font-size: 28rpx;
						color: $text-color;
					}
				}
			}
		}
	}
</style>
